package com.example.contractcontentprovidertest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    //这个最好动态申请权限；这样的用户交互才会有一定的效果！
    private static String[] PERMISSIONS = {
            "android.permission.READ_CONTACTS",
            "android.permission.WRITE_CONTACTS"
    };
    //还是可以参考《第一行代码》中的申请方式
    private static Boolean All_GRANTED = false;
    //UI
    private Button btnAllContracts;
    private RecyclerView recycler_view_contract;
    List<Map> contracts;
    //RecyclerView asserts
    LinearLayoutManager linearLayoutManager;
    ContractRecyclerAdapter contractRecyclerAdapter;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnAllContracts = findViewById(R.id.btn_all_contracts);
        recycler_view_contract = findViewById(R.id.recycler_view_contract);
        checkPermission();
        btnAllContracts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    showAllContracts();
                    btnAllContracts.setVisibility(View.GONE);//button 实现他的功能后进行视图隐藏
                }
            });
        if(!btnAllContracts.isClickable()){
            Toast.makeText(getApplicationContext(),"请申请权限先！",Toast.LENGTH_SHORT).show();
        }
    }
//权限申请
    private void checkPermission() {
        for (String permission : PERMISSIONS){
            if( ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED){
             //自己弹出一个权限获取UI交互
                ActivityCompat.requestPermissions(MainActivity.this,PERMISSIONS,1);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if(grantResults.length > 0 && allPermissions(grantResults)){
                    btnAllContracts.setClickable(true);
                }
                    break;
        }

    }

    private boolean allPermissions(int[] grantResults) {
        for (int i : grantResults){
            if(i != PackageManager.PERMISSION_GRANTED){
                return false;
            }
        }
        return true;
    }

    private void showAllContracts() {
        // ContentProvider的主要实例
        contracts = new ArrayList<Map>();
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
        //遍历-获取每一个通讯者的相关信息
        while(cursor.moveToNext()){
            Map man = new HashMap();
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            man.put("name",name);
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.NAME_RAW_CONTACT_ID));
            Cursor cursor_phone = resolver.query(ContactsContract.Data.CONTENT_URI,null, ContactsContract.Contacts.Entity.RAW_CONTACT_ID +"=?" ,new String[]{id},null);
           ArrayList<String> phones = new ArrayList<>();
            while(cursor_phone.moveToNext()){
                String phone = cursor_phone.getString(cursor_phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
                if(phone != null){
                    phones.add(phone);
                }
            }
            man.put("phones",phones);
            contracts.add(man);
        }
        //更新RecyclerView
        if(contracts.size() != 0){
            Toast.makeText(getApplicationContext(),"通讯录中共有通讯者人数："+contracts.size(),Toast.LENGTH_SHORT).show();
            refreshRecyclerView();
        }else{
            Toast.makeText(getApplicationContext(),"查无此人",Toast.LENGTH_SHORT).show();
        }


    }


    private void refreshRecyclerView() {
        contractRecyclerAdapter = new ContractRecyclerAdapter(contracts);
        linearLayoutManager = new LinearLayoutManager(this);
        recycler_view_contract.setAdapter(contractRecyclerAdapter);
        recycler_view_contract.setLayoutManager(linearLayoutManager);
        contractRecyclerAdapter.notifyDataSetChanged();
    }
}